import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'dart:io';

import '../../../common/index.dart';
import '../utils/image_cache_utils.dart';

class MessageBubble extends StatelessWidget {
  const MessageBubble({
    super.key,
    required this.message,
    required this.isCurrentUser,
    required this.currentUser,
    required this.partnerUser,
    required this.imageCacheUtils,
    this.onImageTap,
  });

  final MessageEntity message;
  final bool isCurrentUser;
  final UserEntity? currentUser;
  final UserEntity? partnerUser;
  final ImageCacheUtils imageCacheUtils;
  final void Function(String imageUrl, String heroTag)? onImageTap;

  @override
  Widget build(BuildContext context) {
    return message.type == MessageType.text
        ? _buildTextMessageWithAvatar()
        : _buildImageMessageWithAvatar();
  }

  // 构建文字消息和头像
  Widget _buildTextMessageWithAvatar() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        // 对方用户头像（左下角）
        if (!isCurrentUser) ...[
          _buildAvatar(partnerUser?.avatar),
          SizedBox(width: 8.w),
        ],
        // 消息内容
        Flexible(child: _buildTextBubble()),
        // 当前用户头像（右下角）
        if (isCurrentUser) ...[
          SizedBox(width: 8.w),
          _buildAvatar(currentUser?.avatar),
        ],
      ],
    );
  }

  // 构建图片消息和头像
  Widget _buildImageMessageWithAvatar() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 对方用户头像（左侧）
        if (!isCurrentUser) ...[
          _buildAvatar(partnerUser?.avatar),
          SizedBox(width: 8.w),
        ],
        // 图片内容
        Flexible(child: _buildImageBubble()),
        // 当前用户头像（右侧）
        if (isCurrentUser) ...[
          SizedBox(width: 8.w),
          _buildAvatar(currentUser?.avatar),
        ],
      ],
    );
  }

  // 构建头像
  Widget _buildAvatar(String? avatarPath) {
    return Container(
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        border: Border.all(color: Colors.white, width: 2.w),
      ),
      child: UserAvatar(
        radius: 22.5.r, // 45.r / 2 = 22.5.r
        avatarPath: avatarPath,
        fallbackAsset: MyImages.mark,
      ),
    );
  }

  // 文字消息气泡
  Widget _buildTextBubble() {
    return Container(
      constraints: BoxConstraints(maxWidth: 245.w),
      padding: EdgeInsets.only(left: 21.w, right: 15.w, top: 9.h, bottom: 9.h),
      decoration: ShapeDecoration(
        color: isCurrentUser
            ? const Color(0xFFFF8C00)
            : const Color(0xFFE94245),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(15.r),
            topRight: Radius.circular(10.r),
            bottomLeft: Radius.circular(isCurrentUser ? 15.r : 0.r),
            bottomRight: Radius.circular(isCurrentUser ? 0.r : 15.r),
          ),
        ),
      ),
      child: Text(
        message.content,
        style: TextStyle(
          color: Colors.white,
          fontSize: 14.sp,
          fontFamily: 'Roboto',
          fontWeight: FontWeight.w400,
          height: 1.h,
        ),
      ),
    );
  }

  // 图片消息气泡
  Widget _buildImageBubble() {
    // 优先检查缓存，避免不必要的 FutureBuilder
    final cachedSize = imageCacheUtils.getCachedImageSize(message.content);
    if (cachedSize != null) {
      return _buildImageWithSize(message.content, cachedSize);
    }

    // 使用 StatefulBuilder 来更好地控制状态，避免键盘变化时的重建问题
    return StatefulBuilder(
      builder: (context, setState) {
        // 再次检查缓存（StatefulBuilder 内部）
        final latestCachedSize = imageCacheUtils.getCachedImageSize(
          message.content,
        );
        if (latestCachedSize != null) {
          return _buildImageWithSize(message.content, latestCachedSize);
        }

        // 如果没有缓存，异步获取尺寸
        imageCacheUtils
            .getImageSize(message.content)
            .then((size) {
              // 获取到尺寸后，触发重建
              if (context.mounted) {
                setState(() {});
              }
            })
            .catchError((error) {
              // 错误处理，使用默认尺寸
              debugPrint('🖼️ 获取图片尺寸失败: $error');
            });

        // 在等待期间显示占位符
        return _buildImagePlaceholder();
      },
    );
  }

  // 构建加载占位符
  Widget _buildImagePlaceholder() {
    return Container(
      width: 150.w,
      height: 150.h,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.r),
        color: Colors.grey[300],
        border: Border.all(
          color: isCurrentUser
              ? const Color(0xFFFFD29B)
              : const Color(0xFFE94245),
          width: 1.w,
        ),
      ),
      child: Center(
        child: CircularProgressIndicator(
          color: isCurrentUser
              ? const Color(0xFFFFD29B)
              : const Color(0xFFE94245),
        ),
      ),
    );
  }

  // 根据尺寸构建图片
  Widget _buildImageWithSize(String imageUrl, Size imageSize) {
    // 设置聊天图片的最大尺寸限制 - 更小更适合聊天界面
    final maxWidth = 200.w; // 固定最大宽度
    final maxHeight = 200.h; // 固定最大高度

    double displayWidth = imageSize.width;
    double displayHeight = imageSize.height;

    // 计算缩放比例，选择更小的比例以确保图片完全适应限制
    final widthRatio = maxWidth / displayWidth;
    final heightRatio = maxHeight / displayHeight;
    final scaleFactor = widthRatio < heightRatio ? widthRatio : heightRatio;

    // 应用缩放比例
    displayWidth = displayWidth * scaleFactor;
    displayHeight = displayHeight * scaleFactor;

    // 确保最小尺寸，避免图片太小
    final minSize = 80.w;
    if (displayWidth < minSize && displayHeight < minSize) {
      final minScaleFactor =
          minSize /
          (displayWidth < displayHeight ? displayWidth : displayHeight);
      displayWidth = displayWidth * minScaleFactor;
      displayHeight = displayHeight * minScaleFactor;
    }

    return GestureDetector(
      onTap: () => _onImageTap(imageUrl),
      child: Hero(
        tag: 'chat_image_${message.id}',
        child: Container(
          width: displayWidth,
          height: displayHeight,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.r),
            border: Border.all(
              color: isCurrentUser
                  ? const Color(0xFFFFD29B)
                  : const Color(0xFFE94245),
              width: 1.w,
            ),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(10.r),
            child: _buildImageWidget(imageUrl, displayWidth, displayHeight),
          ),
        ),
      ),
    );
  }

  // 处理图片点击事件
  void _onImageTap(String imageUrl) {
    if (onImageTap != null) {
      onImageTap!(imageUrl, 'chat_image_${message.id}');
    }
  }

  // 构建图片组件，支持本地文件和assets
  Widget _buildImageWidget(String imageUrl, double width, double height) {
    // 检查是否是相对路径（聊天图片）
    if (!imageUrl.startsWith('assets/') && !imageUrl.startsWith('/')) {
      // 先检查是否有缓存的路径
      final cachedPath = imageCacheUtils.getCachedImagePath(imageUrl);
      if (cachedPath != null) {
        final file = File(cachedPath);
        if (file.existsSync()) {
          return Image.file(
            file,
            width: width,
            height: height,
            fit: BoxFit.cover,
            cacheWidth: width.toInt(),
            cacheHeight: height.toInt(),
            errorBuilder: (context, error, stackTrace) {
              debugPrint('🖼️ 图片加载失败: $error');
              return _buildErrorPlaceholder(width, height);
            },
          );
        }
      }

      // 如果没有缓存，使用 StatefulBuilder 避免键盘变化时的重建
      return StatefulBuilder(
        builder: (context, setState) {
          return FutureBuilder<String?>(
            key: ValueKey('image_path_${message.id}_$imageUrl'),
            future: imageCacheUtils.getFullImagePath(imageUrl),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return Container(
                  width: width,
                  height: height,
                  color: Colors.grey.withValues(alpha: 0.3),
                  child: const Center(
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                    ),
                  ),
                );
              }

              if (snapshot.hasData && snapshot.data != null) {
                final file = File(snapshot.data!);

                if (file.existsSync()) {
                  return Image.file(
                    file,
                    width: width,
                    height: height,
                    fit: BoxFit.cover,
                    // 添加缓存配置，避免重复加载
                    cacheWidth: width.toInt(),
                    cacheHeight: height.toInt(),
                    errorBuilder: (context, error, stackTrace) {
                      debugPrint('🖼️ 图片加载失败: $error');
                      return _buildErrorPlaceholder(width, height);
                    },
                  );
                }
              }

              debugPrint('🖼️ 图片文件不存在或路径为空: $imageUrl');
              // 如果文件不存在，显示错误占位符
              return _buildErrorPlaceholder(width, height);
            },
          );
        },
      );
    }

    // 对于assets图片，使用原来的逻辑
    return Image.asset(
      imageUrl,
      width: width,
      height: height,
      fit: BoxFit.cover,
      // 添加缓存配置
      cacheWidth: width.toInt(),
      cacheHeight: height.toInt(),
      errorBuilder: (context, error, stackTrace) {
        debugPrint('🖼️ Assets图片加载失败: $imageUrl, $error');
        return _buildErrorPlaceholder(width, height);
      },
    );
  }

  // 构建错误占位符
  Widget _buildErrorPlaceholder(double width, double height) {
    return Container(
      width: width,
      height: height,
      color: Colors.grey.withValues(alpha: 0.3),
      child: const Center(
        child: Icon(Icons.broken_image, color: Colors.white, size: 32),
      ),
    );
  }
}
